package com.joesem.sale.client.widget.dialog

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.WindowManager
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.adapter.FragmentViewHolder
import com.bumptech.glide.Glide
import com.jiaxing.sale.client.databinding.DialogImagePreviewBinding
import com.jiaxing.sale.client.databinding.ItemImagePerviewBinding
import com.joesem.sale.client.base.BaseDialog
import com.joesem.sale.client.base.BaseFragment
import com.joesem.sale.client.utils.click


class ImagePreviewDialog(
    context: Context,
    val fm: FragmentManager,
    val img: List<String>,
    private val defaultPosition: Int = 0
) : BaseDialog<DialogImagePreviewBinding>(context) {
    override fun DialogImagePreviewBinding.initView() {
        window?.setBackgroundDrawable(ColorDrawable(Color.parseColor("#99000000")))
        window?.setLayout(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT
        )
        vpImgContent.adapter = object : FragmentStateAdapter(fm, lifecycle) {

            override fun getItemCount() = img.size

            override fun createFragment(position: Int): Fragment {
                return BaseFragment.newInstance<ImgFragment>(Bundle().apply {
                    putString("img", img[position])
                }).apply {
                    clickImg={
                        dismiss()
                    }
                }
            }

            override fun onBindViewHolder(
                holder: FragmentViewHolder,
                position: Int,
                payloads: MutableList<Any>
            ) {
                super.onBindViewHolder(holder, position, payloads)
                holder.itemView.click {

                }
            }
        }
        if (defaultPosition < img.size)
            vpImgContent.currentItem = defaultPosition
    }

    class ImgFragment : BaseFragment<ItemImagePerviewBinding>() {
        var clickImg: () -> Unit = {}
        override fun ItemImagePerviewBinding.initView(savedInstanceState: Bundle?) {
            Glide.with(requireContext()).load(arguments?.getString("img")).into(ivImage)
            ivImage.click { clickImg.invoke() }
        }
    }
}

fun imagePreview(
    context: Context, fm: FragmentManager,
    img: List<String>,
    defaultPosition: Int = 0
) {
    ImagePreviewDialog(context, fm, img, defaultPosition).show()
}